package com.xunfang.config.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xunfang.config.service.FlowLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
public class SentinelClientController{

    @GetMapping("/testA")
    public String testA(){
        return "hello testA" + UUID.randomUUID().toString();
    }

    @GetMapping("/testB")
    public String testB(){
        return "hello testB" + UUID.randomUUID().toString();
    }

    @Autowired
    private FlowLimitService flowLimitService;

    @GetMapping("/testC")
    public String testC(){
        flowLimitService.common();
        return "------testC";
    }

    @GetMapping("/testD")
    public String testD(){
        flowLimitService.common();
        return "------testD";
    }

    @GetMapping("/rateLimit/doAction/{p1}")
    @SentinelResource(
            value = "doActionSentinelResource",  //名称
            blockHandler = "doActionBlockHandler", //处理BlockException的函数名称
            fallback = "doActionFallback")          // 抛出异常的时候提供fallback处理逻辑
    public String doAction(@PathVariable("p1") Integer p1) {
        if (p1 == 0){
            throw new RuntimeException("p1等于零直接异常");
        }
        return "doAction";
    }

    //流控         人员比较多 网络繁忙
    public String doActionBlockHandler(@PathVariable("p1") Integer p1, BlockException e){
        log.error("sentinel配置自定义限流了:{}", e);
        return "sentinel配置自定义限流了";
    }

    //服务降级 处理异常     支付失败 (阿里那边程序出问题)
    public String doActionFallback(@PathVariable("p1") Integer p1,Throwable e){
        log.error("程序逻辑异常了:{}", e);
        return "程序逻辑异常了"+"\t"+e.getMessage();
    }
}